<template>
    <div>
        <!-- 实名认证组件的结构 -->
        <el-card class="box-card">
            <!-- 卡片的头部 -->
            <template #header>
                <div class="card-header">
                    实名信息
                </div>
            </template>
            <!-- 实名认证结构的提示部分 -->
            <div class="tip">
                <p><el-icon>
                        <InfoFilled />
                    </el-icon>完成实名认证后才能添加就诊人，正常进行挂号</p>
            </div>
            <!-- 卡片的底部认证成功的结构 -->
            <el-descriptions v-if="userInfo.authStatus === 1" class="margin-top" :column="1" border>

                <el-descriptions-item width="20px" label-align="center">
                    <template #label>
                        <div class="cell-item">
                            用户姓名
                        </div>
                    </template>
                    {{ userInfo.name }}
                </el-descriptions-item>
                <el-descriptions-item width="20px" label-align="center">
                    <template #label>
                        <div class="cell-item">
                            证件类型
                        </div>
                    </template>
                    {{ userInfo.certificatesType=10 ? "身份证" : "户口本" }}
                </el-descriptions-item>
                <el-descriptions-item width="20px" label-align="center">
                    <template #label>
                        <div class="cell-item">
                            证件号码
                        </div>
                    </template>
                    {{ userInfo.certificatesNo }}
                </el-descriptions-item>
            </el-descriptions>
            <!-- 用户未验证的结构 -->
            <el-form ref="form" :model="params" :rules="rules" v-if="userInfo.authStatus === 0"
                style="width: 60%; margin: 20px auto;" label-width="80px">
                <el-form-item label="用户姓名" prop="name">
                    <el-input placeholder="请输入用户姓名" v-model="params.name"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" prop="certificatesType">
                    <el-select placeholder="请输入证件类型" style="width: 100%;" v-model="params.certificatesType">
                        <el-option v-for="(item, index) in arrType" :key="index" :label="item.name"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证号" prop="certificatesNo">
                    <el-input placeholder="请输入身份证号" v-model="params.certificatesNo"></el-input>
                </el-form-item>
                <el-form-item label="上传证件" prop="certificatesUrl">
                    <!-- action:upload 组件向服务器提交的图片路径
                        limit 最大数量
                        on-exceed 超出最大数量的钩子
                    -->
                    <el-upload list-type="picture-card" action="/api/oss/file/fileUpload?fileHost=userAuah" :limit="1"
                        :on-exceed="exceedHandler" :on-success="successHandler" :on-remove="removeHandler"
                        :on-preview="previewHandler" ref="upload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisable">
                        <img w-full style="width: 100%; height: 100%;" :src="params.certificatesUrl" alt="Preview Image">
                    </el-dialog>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="default" @click="submit">提交</el-button>
                    <el-button type="primary" size="default" @click="reset">重写</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { InfoFilled, Plus } from '@element-plus/icons-vue';
import { reqUserinfo, reqCertationType, reqUserCertation } from '@/api/user/index'
import type { UserInfoResponseData, CertationArr, CertationTypeResponseData } from '@/api/user/type'
import { onMounted, ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

let arrType = ref<CertationArr>([])
let userInfo = ref<any>({})
// 收集用户表单信息
let params = reactive({
    certificatesNo: '',
    certificatesType: '',
    certificatesUrl: '',
    name: ''
})
// 控制对话框的显示与隐藏
let dialogVisable = ref<boolean>(false)

let upload = ref()
let form = ref()
// 组件挂载完毕
onMounted(() => {
    getUserInfo()
    getType()
})
// 获取用户信息的方法
const getUserInfo = async () => {
    const result: UserInfoResponseData = await reqUserinfo()
    
    if (result.code === 200) {
        userInfo.value = result.data
    }

}
// 获取证件类型的接口
const getType = async () => {
    const result: CertationTypeResponseData = await reqCertationType()
    if (result.code === 200) {
        arrType.value = result.data
    }
}
// 当超出限制时，执行的钩子函数
const exceedHandler = () => {
    ElMessage({
        type: 'error',
        message: '图片只能上传一张'
    })
}
// 文件上传成功时的钩子
const successHandler = (response: any) => {
    form.value.clearValidate('certificatesUrl')
    // 收集上传成功的的图片地址
    params.certificatesUrl = response.data
}
// 文件列表移除文件时的钩子
const removeHandler = () => {
    params.certificatesUrl = ''
}
// 文件预览的钩子
const previewHandler = () => {
    // 触发预览的钩子，展示对话框
    dialogVisable.value = true
}
// 重写的按钮回调
const reset = () => {
    params.certificatesNo = '',
        params.name = '',
        params.certificatesType = ''
    // 清除文件上传列表
    upload.value.clearFiles()

}
//提交按钮回调 
const submit = async () => {
    // 整个表单进行校验成功返回成功的promise，失败返回失败的promise
    await form.value.validate()
    try {
        await reqUserCertation(params)
        ElMessage({
            type: 'success',
            message: '提交成功'
        });
        // 认证成功再次获取用户信息
        getUserInfo()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '提交失败'
        })
    }

}
// 自定义校验姓名规则方法
const validatorName = (rule: any, value: any, callback: any) => {
    const reg = /^[\u00B7\u3007\u3400-\u9FFF\uE000-\uF8FF\uF900-\uFAFF\u{20000}-\u{2FFFF}\u{30000}-\u{3FFFF}]+$/u;
    if (reg.test(value)) {
        callback()
    } else {
        callback(new Error('请输入正确的中国人的名字'))
    }
}
// 自定义校验证件类型规则方法
const certificatesType = (rule: any, value: any, callback: any) => {
    if (value == 10 || value == 20) {
        callback()
    } else {
        callback(new Error('请选择正确的类型'))
    }
}
// 自定义校验户口本和身份证规则方法
const certificatesNo = (rule: any, value: any, callback: any) => {
    const sfz = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    const hkb = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (sfz.test(value) || hkb.test(value)) {
        callback()
    } else {
        callback(new Error('请输入正确的身份证或户口本'))
    }
}
// 自定义校验图片规则方法
const certificatesUrl = (rule: any, value: any, callback: any) => {
    if (value.length) {
        callback()
    } else {
        callback(new Error('请上传图片'))
    }
}
// 表单校验规则对象
const rules = {
    // 用户姓名校验规则
    name: [{
        required: true,
        validator: validatorName,
    }],
    certificatesType: [{
        required: true,
        validator: certificatesType,
    }],
    certificatesNo: [{
        required: true,
        validator: certificatesNo,
    }],
    certificatesUrl: [{
        required: true,
        validator: certificatesUrl,
    }]
}




</script>

<style scoped lang="scss">
.tip {
    color: #7f7f7f;
    margin: 10px auto;
    display: flex;
    justify-content: center;
}
</style>